package cn.com.controller.frontController;


import cn.com.Enum.SessionAttr;
import cn.com.Enum.UserAuth;
import cn.com.annotation.Auth;
import cn.com.constant.Code;
import cn.com.db.model.User;
import cn.com.db.service.UserService;
import cn.com.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


@Auth(UserAuth.USER)
@RestController
@RequestMapping("/front/user/")
public class UserController {

    Logger logger=Logger.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @Auth(UserAuth.ALL)
    @RequestMapping(value = "register",method = RequestMethod.POST)
    public void register(HttpServletRequest request,HttpServletResponse response,
                           @RequestParam("authingId")String authingId,
                           @RequestParam("wechatInfo")String wechatInfo,
                           @RequestParam("token")String token,
                           @RequestParam(value = "openid",required = false)String openId)
    {
        DataResult dataResult=new DataResult();
        JSONObject json = JSON.parseObject(wechatInfo);
		openId = (String) json.get("unionid");   // 前端传的openId不管
        if (StringUtils.isBlank(openId)){
            dataResult.setCode(Code.UN_AUTHORIZED);
            dataResult.setMessage("无法获取用户授权信息");
            util.comeBack(response,JSON.toJSONString(dataResult));
        }
//        User user=userService.getUserByOpenId(openId);
        User user=userService.getUserAuthingId(authingId);
        if (user!=null){
            user.setToken(token);
            user.setWechat_info(wechatInfo);
            userService.update(user);
            dataResult.setCode(Code.SUCCESS);
            dataResult.setMessage("注册成功");
            util.comeBack(response,JSON.toJSONString(dataResult));
            return;
        }
        user=new User();
        user.setAuthing_id(authingId);
        user.setWechat_info(wechatInfo);
        user.setCreated_at(TimeUtil.getNowTimestamp());
        user.setUpdated_at(TimeUtil.getNowTimestamp());
        user.setId(UidUtil.createUUID());
        user.setToken(token);
        user.setOpenId(openId);
        userService.createUser(user);
//        用户id存session
        SessionUtil.addAttr(request,SessionAttr.USERAUTHINGID,user.getAuthing_id());
        dataResult.setCode(Code.SUCCESS);
        dataResult.setMessage("注册成功");
        dataResult.setData(user);
        response.setHeader("token",TokenUtil.createToken(user.getId(),UserAuth.USER));
        util.comeBack(response,JSON.toJSONString(dataResult));
    }


    @Auth(UserAuth.ALL)
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public void login(HttpServletRequest request,HttpServletResponse response,
                           @RequestParam("authingId")String authingId)
    {
        DataResult dataResult=new DataResult();
        User user=userService.getUserAuthingId(authingId);
        if (user==null){
            dataResult.setCode(Code.UN_AUTHORIZED);
            dataResult.setMessage("登录失败,用户authing不存在");
            util.comeBack(response,JSON.toJSONString(dataResult));
            return;
        }
        SessionUtil.addAttr(request,SessionAttr.USERAUTHINGID,user.getAuthing_id());
        dataResult.setCode(Code.SUCCESS);
        dataResult.setMessage("登录成功");
        dataResult.setData(user);
        response.setHeader("token",TokenUtil.createToken(user.getId(),UserAuth.USER));
        util.comeBack(response,JSON.toJSONString(dataResult));
    }


}
